properties([
        parameters([
                [$class: 'ChoiceParameter',
                 choiceType: 'PT_CHECKBOX',
                 description: '请选择要合并的分支（可多选）',
                 name: 'BRANCHES',
                 script: [
                         $class: 'GroovyScript',
                         fallbackScript: [script: 'return ["ERROR"]'],
                         script: [sandbox: false, script: '''
                // 执行 git 命令
                def cmd = "git ls-remote --heads http://gitlab.esaas.net/yinline/yinline.git"
                def proc = cmd.execute()
                proc.waitFor()
                def text = proc.in.text

                // 解析分支
                def branches = text.readLines().collect { line ->
                    def parts = line.tokenize("\\t")
                    parts.last().replaceAll("refs/heads/", "")
                }

                // 去掉空分支
                branches = branches.findAll { it?.trim() }

                return branches
             ''']
                 ]
                ]
        ])
])

pipeline {
    agent any

    stages {
        stage('Prepare Branch') {
            steps {
                script {
                    // Workspace
                    def workspace = env.WORKSPACE
                    def lastFile = "${workspace}\\.last_release_branch"

                    // 上一次临时分支及选择列表
                    def lastBranch = null
                    def lastSelected = null
                    if (fileExists(lastFile)) {
                        def lines = readFile(lastFile).split("\n")
                        if (lines.size() >= 1) lastBranch = lines[0].trim()
                        if (lines.size() >= 2) lastSelected = lines[1].trim()
                    }

                    // 当前选择分支
                    def currentSelected = params.BRANCHES.split(",").collect { it.trim() }.sort().join(",")

                    // 是否复用临时分支
                    def releaseBranch
                    if (lastBranch && lastSelected == currentSelected) {
                        echo "分支未变化，复用上一次临时分支: ${lastBranch}"
                        releaseBranch = lastBranch
                    } else {
                        if (lastBranch) {
                            echo "分支列表变化，删除上一次临时分支: ${lastBranch}"
                            // 删除临时分支（本地 + 远程）
                            bat """
                                    cd repo
                                    REM 删除本地分支（如果存在）
                                    git show-ref --verify --quiet refs/heads/${lastBranch}
                                    if %ERRORLEVEL%==0 (
                                        git branch -D ${lastBranch}
                                    ) else (
                                        echo 本地分支不存在
                                    )
                                    exit /b 0
                            
                                    REM 删除远程分支（如果存在）
                                    git ls-remote --exit-code --heads origin ${lastBranch}
                                    if %ERRORLEVEL%==0 (
                                        git push origin --delete ${lastBranch}
                                    ) else (
                                        echo 远程分支不存在
                                    )
                                    exit /b 0
                            """
                        }else {
                            echo "上一次临时分支为空，无需删除"
                        }

                        releaseBranch = "release_${UUID.randomUUID().toString().replace('-', '')}"
                        echo "生成新的临时分支: ${releaseBranch}"
                    }

                    env.RELEASE_BRANCH = releaseBranch

                    // 准备 repo
                    if (fileExists("${workspace}\\repo")) {
                        echo "repo 已存在，重置到 origin/main"
                        bat """
                        cd repo
                        git fetch origin
                        git checkout main
                        git reset --hard origin/main
                        git clean -fdx
                        """
                    } else {
                        echo "repo 不存在，克隆仓库"
                        bat """
                        git clone http://gitlab.esaas.net/yinline/yinline.git repo
                        cd repo
                        git checkout -b main origin/main
                        """
                    }

                    // 创建临时分支
                    bat """
                        cd repo
                        git checkout -B ${releaseBranch}
                        git config user.name "konghong"
                        git config user.email "wah1763751448@163.com"
                        """
                    // 合并选择分支
                    params.BRANCHES.split(",").each { b ->
                        bat """
                        cd repo
                        git fetch origin ${b}
                        git merge --no-ff origin/${b} -m "Merge branch ${b} into ${releaseBranch}"
                        """
                    }

                    // 保存临时分支信息
                    writeFile file: lastFile, text: "${releaseBranch}\n${currentSelected}"
                }
            }
        }

        stage('Check Java') {
            steps {
                bat 'java -version'
            }
        }

        stage('Build with Maven') {
            steps {
                bat """
                    cd repo
                    mvn clean install -DskipTests
                """
            }
        }

        stage('Result') {
            steps {
                echo "已完成临时分支 ${env.RELEASE_BRANCH} 的合并和构建"
            }
        }
    }
}
